#!/bin/bash

# 登陆信息
mysql_user_id="root"
mysql_password="Sjy.1234"
# mysql url
mysql_host="mydb"
# 指定字符集
mysql_opts="--default-character-set=utf8"

# 文件路径接口
url_init_sql="./delete_poidb_tables.sql"
url_ddl_sql="./ddl.sql"
url_data_sql_root="./data"

exec_sql() {
    local sql_file="$1"
    if [ ! -f "$sql_file" ]; then
        echo "Error: SQL file not found at $sql_file"
        exit 1
    fi

    # 检查执行结果
    if mysql $mysql_opts -u$mysql_user_id -p"$mysql_password" -h$mysql_host < "$sql_file"; then
        echo "SQL file $sql_file executed successfully"
    else
        echo "Error: Failed to execute SQL file $sql_file"
        exit 1
    fi
}

exec_import_data() {
    local sql_file="$1"
    # 关闭外键约束检查
    echo "Disabling foreign key checks..."
    mysql $mysql_opts -u"$mysql_user_id" -p"$mysql_password" -h"$mysql_host" <<EOF
SET FOREIGN_KEY_CHECKS = 0;
source $sql_file
SET FOREIGN_KEY_CHECKS = 1;
EOF
}

# 初期化
if ! exec_sql "$url_init_sql"; then
    exit 1
fi

# 创建ddl
if ! exec_sql "$url_ddl_sql"; then
    exit 1
fi

# 导入数据
for file in "$url_data_sql_root"/*; do
    # 只处理文件
    if [ -f "$file" ];then
        # 获取文件扩展名
        extension="${file##*.}"

        if [ "$extension" = "sql" ]; then
            # 执行导入
            if ! exec_import_data "$file"; then
                echo "Error: Failed to execute SQL file $file"
                exit 1
            else
                echo "SQL file $file executed successfully"
            fi
        fi
    fi
done